package com.xusheng.cli.controller.proxy;

import cn.hutool.core.util.RandomUtil;
import com.apistd.uni.Uni;
import com.apistd.uni.UniException;
import com.apistd.uni.UniResponse;
import com.apistd.uni.sms.UniMessage;
import com.apistd.uni.sms.UniSMS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.Result;
import com.xusheng.cli.common.validation.Save;
import com.xusheng.cli.common.validation.Update;
import com.xusheng.cli.config.SmsSendConfig;
import com.xusheng.cli.entity.bankCardModule.BankCard;
import com.xusheng.cli.service.BankCardService;
import com.xusheng.cli.thiredparty.entity.AuthResult;
import com.xusheng.cli.thiredparty.entity.BankAuthCode;
import com.xusheng.cli.thiredparty.service.ThiredpartyService;
import com.xusheng.cli.thiredparty.util.SMSVerificationCode;
import com.xusheng.cli.tools.CurrentProxyUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 银行卡表(BankCard)表控制层
 *
 * @author whr
 * @since 2024-03-19 17:26:37
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/proxy/v1/bankCard")
public class BankCardController {
    /**
     * 服务对象
     */
    @Resource
    private BankCardService bankCardService;
    @Resource
    private ThiredpartyService thiredpartyService;

    private static final int EXPIRE_MIN = 5;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询所有数据
     *
     * @param bankCard 查询实体
     * @return 所有数据
     * @author whr
     * @since 2024-03-19 17:26:37
     */
    @GetMapping("queryAll")
    public Result<List<BankCard>> queryAll(BankCard bankCard) {
        return Result.success(bankCardService.list(new QueryWrapper<>(bankCard)));
    }

    /**
     * 分页查询所有数据
     *
     * @param page     分页对象
     * @param bankCard 查询实体
     * @return 所有数据
     * @author whr
     * @since 2024-03-19 17:26:37
     */
    @GetMapping("queryByPage")
    public Result<MyPage<BankCard>> queryByPage(MyPage<BankCard> page, BankCard bankCard) {
        bankCard.setOwnerId(CurrentProxyUserUtil.getUserId());
        return Result.success(bankCardService.page(page, new QueryWrapper<>(bankCard)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     * @author whr
     * @since 2024-03-19 17:26:37
     */
    @GetMapping("queryOne/{id}")
    public Result<BankCard> selectOne(@PathVariable Serializable id) {
        return Result.success(bankCardService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param bankCard 实体对象
     * @return 新增结果
     * @author whr
     * @since 2024-03-19 17:26:37
     */
    @PostMapping("insert")
    public Result<Object> insert(@Validated(Save.class) @RequestBody BankCard bankCard) {
/*        String key = SMSVerificationCode.PHONE_PASSWORD_KEY + bankCard.getMobile();
        String c = redisTemplate.opsForValue().get(key);
        log.info("key={}, redis-code = {}, user-code={}", key, c, bankCard.getCode());
        if (StrUtil.isBlank(c) || !c.equals(bankCard.getCode())) {
            return Result.error("短信验证码不正确");
        }
        redisTemplate.delete(key);*/
        Long userId = CurrentProxyUserUtil.getUserId();
//        BackAgent user = backAgentService.getById(userId);
//        if (StrUtil.isBlank(user.getIdentityCard())) {
//            return Result.error("请先实名认证");
//        }
        AuthResult result = thiredpartyService.bankAuth(bankCard.getCardNo(), bankCard.getIdCard(), bankCard.getMobile(), bankCard.getName());
        if (!BankAuthCode.C10000.code().equals(result.getCode())) {
            return Result.error("银行卡认证失败");
        }
        if (!AuthResult.State.SAME.code().equals(result.getData().getState())) {
            return Result.error("请检查银行卡信息是否正确");
        }
        bankCard.setOwnerId(userId);
        long count = bankCardService.count(new LambdaQueryWrapper<>(new BankCard()).eq(BankCard::getOwnerId, userId));
        bankCard.setCardDefault(count == 0);
        return Result.isSuccess(bankCardService.save(bankCard));
    }

    @PostMapping("sendSms")
    public Result<Map<String, Object>> sendSms(@RequestBody Map<String, String> map) {
        String code = RandomUtil.randomNumbers(6);
        SmsSendConfig config = new SmsSendConfig();
        // 初始化
        Uni.init(config.getAccessKeyId()); // 若使用简易验签模式仅传入第一个参数即可
        // 设置自定义参数 (变量短信)
        Map<String, String> templateData = new HashMap<String, String>();
        templateData.put("code", code);

        // 构建信息
        UniMessage message = UniSMS.buildMessage()
                .setTo(map.get("mobile"))
                .setSignature("坪鹰")
                .setTemplateId("pub_verif_basic")
                .setTemplateData(templateData);
        // 发送短信
        try {
            UniResponse res = message.send();
            System.out.println(res);
            if (res.code.equals("0")) {
                String key = SMSVerificationCode.PHONE_PASSWORD_KEY + map.get("mobile");
                redisTemplate.opsForValue().set(key, code, EXPIRE_MIN, TimeUnit.MINUTES);
                return Result.success("验证码发送成功", null);
            } else {
                return Result.error("验证码发送失败");
            }
        } catch (UniException e) {
            System.out.println("Error: " + e);
            System.out.println("RequestId: " + e.requestId);
            return Result.error("验证码发送失败");
        }
    }

    /**
     * 修改数据
     *
     * @param bankCard 实体对象
     * @return 修改结果
     * @author whr
     * @since 2024-03-19 17:26:37
     */
    @PutMapping("update")
    public Result<Object> update(@Validated(Update.class) @RequestBody BankCard bankCard) {
        return Result.isSuccess(bankCardService.updateById(bankCard));
    }

    /**
     * 删除单条数据
     *
     * @param id 主键
     * @return 删除结果
     * @author whr
     * @since 2024-03-19 17:26:37
     */
    @DeleteMapping("delete/{id}")
    public Result<Object> delete(@PathVariable Long id) {
        BankCard bankCard = new BankCard();
        bankCard.setId(id);
        return Result.isSuccess(bankCardService.removeById(bankCard));
    }

    /**
     * 批量删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     * @author whr
     * @since 2024-03-19 17:26:37
     */
    @DeleteMapping("batchDelete")
    public Result<Object> batchDelete(@Validated @Size(min = 1, message = "缺少删除所需的id") @RequestParam("idList") List<Long> idList) {
        return Result.isSuccess(bankCardService.batchDelete(idList, new BankCard()));
    }
}

